package com.chat.netty.server;


import com.chat.netty.proto.ServerProto;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chat.netty.handler.WSServerSocketChannel;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: 刘星星
 * @date: 2020/4/22 10:34
 */
@Component
public class WSServer {

    @Autowired
    private ServerProto serverProto;

    @Autowired
    private WSServerSocketChannel wsServerSocketChannel;

    private static final Logger log = LoggerFactory.getLogger(WSServer.class);

    private EventLoopGroup bossgroup = new NioEventLoopGroup(1);

    /** 默认核心数*2 */
    private EventLoopGroup workgroup = new NioEventLoopGroup();


    public void run() throws InterruptedException {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossgroup, workgroup)
                    .option(ChannelOption.SO_BACKLOG, 128)//当线程池全满时，用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1，Java将使用默认值50
                    .channel(NioServerSocketChannel.class)
                    .childHandler(wsServerSocketChannel);
            ChannelFuture channelFuture = serverBootstrap.bind(serverProto.getPort()).sync();
            if (channelFuture != null && channelFuture.isSuccess()) {
                log.info("Netty server 服务启动成功，端口port = {}", serverProto.getPort());
            } else {
                log.info("Netty server start fail");
            }
        }finally {
            log.info("Netty server 关闭");
//            shutdown();
        }
    }


    /**
     * 优雅的关闭主从线程
     */
    public void shutdown(){
        bossgroup.shutdownGracefully();
        workgroup.shutdownGracefully();
    }

}
